/**
 * Copyright 2006 gworks.com.au
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. (http://www.apache.org/licenses/LICENSE-2.0)
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed 
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
 * the specific language governing permissions and limitations under the License.
 *
 * <dhamma-message src="Atisha (11th century Tibetan Buddhist master)">
 * 	The greatest achievement is selflessness. The greatest worth is self-mastery.
 * 	The greatest quality is seeking to serve others. The greatest precept is continual awareness.
 * 	The greatest medicine is the emptiness of everything. The greatest action is not conforming with the worlds ways.
 * 	The greatest magic is transmuting the passions. The greatest generosity is non-attachment.
 * 	The greatest goodness is a peaceful mind. The greatest patience is humility.
 * 	The greatest effort is not concerned with results. The greatest meditation is a mind that lets go.
 * 	The greatest wisdom is seeing through appearances. 
 * </dhamma-message>
 */
package au.com.gworks.jump.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class TimeUtils {
	private TimeUtils() {
		// class utility
	}

	private static final DateFormat ISO8601_DATE_FORMAT = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss.SSS'000Z'");

	private static final Calendar GMT_CALENDAR = Calendar.getInstance(TimeZone
			.getTimeZone("GMT"));

	static {
		ISO8601_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
	}

	public static String formatDate(long dateAsLong) {
		return formatDate(new Date(dateAsLong));
	}
	
	public static String formatDate(Date date) {
		if (date == null || date.getTime() == 0) {
			return null;
		}
		return ISO8601_DATE_FORMAT.format(date);
	}

	public static Date parseDate(String str) {
		if (str == null) {
			return null;
		}
		try {
			return new Date(parseDateAsLong(str));
		} catch (Throwable th) {
			//
		}
		return null;
	}

	private static final char[] DATE_SEPARATORS = { '-', '-', 'T', ':', ':',
			'.', 'Z' };

	public static long parseDateAsLong(String str) {
		if (str == null) {
			return -1;
		}
		int index = 0;
		int charIndex = 0;
		int startIndex = 0;
		int[] result = new int[7];
		int strLen = str.length();
		while (index < DATE_SEPARATORS.length && charIndex < strLen) {
			if (str.charAt(charIndex) == DATE_SEPARATORS[index]) {
				String segment = str.substring(startIndex, charIndex);
				int segmentLen = segment.length(); 
				if (segmentLen == 0) {
					result[index] = 0;
				} else if (index + 1 < DATE_SEPARATORS.length) {
					result[index] = Integer.parseInt(segment);
				} else {
					result[index] = Integer.parseInt(segment.substring(0, Math
							.min(3, segmentLen)));
				}
				startIndex = charIndex + 1;
				index++;
			}
			charIndex++;
		}
		int year = result[0];
		int month = result[1];
		int date = result[2];

		int hour = result[3];
		int min = result[4];
		int sec = result[5];
		int ms = result[6];

		GMT_CALENDAR.clear();
		GMT_CALENDAR.set(year, month - 1, date, hour, min, sec);
		GMT_CALENDAR.set(Calendar.MILLISECOND, ms);
		return GMT_CALENDAR.getTimeInMillis();
	}
	
	static public long toSystemTime(long utcTime) {
		return toZonedTime(utcTime, TimeZone.getDefault());
	}

	static public Date toZonedTime(Date utcTime, TimeZone tz) {
		return new Date(toZonedTime(utcTime.getTime(), tz));
	}
	
	static public long toZonedTime(long utcTime, TimeZone tz) {
		return utcTime;
	}
	
}